"""
部门管理视图函数
功能：实现部门的增删改查
"""
from django.shortcuts import render, redirect

from app import models
from app.models import Department  # 数据表类


def depart_list(request):
    """
    部门列表
    """
    data_list = Department.objects.all()
    for item in data_list:
        print(item.id)
    return render(request, 'depart_list.html', {'queryset': data_list})


def depart_add(request):
    """
    新增部门
    """
    if request.method == 'GET':
        return render(request, 'depart_add.html')

    title = request.POST.get('title')

    Department.objects.create(title=title)
    return redirect('/depart/list')


def depart_delete(request):
    """
    删除部门
    """
    nid = request.GET.get('nid')
    Department.objects.filter(id=nid).delete()
    return redirect('/depart/list')


def depart_edit(request, nid):
    """
    编辑部门
    nid 用于接收前端传递过来的id,他的名字要和urls.py文件中定义的一样
    """
    if request.method == 'GET':  # 进入编辑页面
        row_object = Department.objects.filter(id=nid).first()
        return render(request, 'depart_edit.html', {'row_object': row_object})

    # 保存修改POST提交
    title = request.POST.get('title')
    Department.objects.filter(id=nid).update(title=title)
    return redirect('/depart/list')


def depart_multi(request):
    """ 批量上传文件 (excel文件） """
    from django.core.files.uploadedfile import InMemoryUploadedFile

    file_object = request.FILES.get('exc')  # 从depart_list.html中读取上传的文件
    # 直接打开excel文件并读取
    from openpyxl import load_workbook
    wb = load_workbook(file_object)  # load_workbook可以打开一个文件对象
    sheet = wb.worksheets[0]  # 第1个工作薄
    # row = sheet.cell(1, 1)  # xls表第1行，第1列数据
    # print(row.value)

    # 循环读取所有行
    # 第1行是标题，数据从第2行开始读取
    for row in sheet.iter_rows(min_row=2):
        data = row[0].value
        if not models.Department.objects.filter(title=data).exists(): # 判断部门值是否存在
            models.Department.objects.create(title=data)

    return redirect('/depart/list')
